<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">
        <span @click="saveState">首页</span>
      </el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入商品名称"
            v-model="queryInfo.query"
            clearable
            @clear="getGoodsList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getGoodsList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="goAddpage">添加商品</el-button>
        </el-col>
      </el-row>

      <!-- table表格区域 -->
      <el-table :data="goodsList" :key="goodsList.goods" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="商品名称" prop="goods_name"></el-table-column>
        <el-table-column
          label="商品价格/元"
          prop="goods_price"
          width="120px"
        ></el-table-column>
        <el-table-column
          label="商品库存(斤)"
          prop="goods_number"
          width="120px"
        ></el-table-column>
        <el-table-column
          label="商品分类"
          prop="cat_name"
          width="120px"
        ></el-table-column>
        <el-table-column label="创建时间" prop="add_time" width="200px">
          <template slot-scope="scope">
            {{ scope.row.add_time | dataFormat }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200px">
          <template slot-scope="scope">
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row._id)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeById(scope.row._id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        background
      >
      </el-pagination>
    </el-card>

    <!-- 修改商品信息的对话框 -->
    <el-dialog
      title="修改商品信息"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClosed"
    >
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="80px"
      >
        <el-form-item label="商品名称"  prop="goods_name">
          <el-input v-model="editForm.goods_name" width="100px"></el-input>
        </el-form-item>
        <el-form-item label="商品价格"  prop="goods_price">
          <el-input v-model="editForm.goods_price" type="number"></el-input>
        </el-form-item>
        <el-form-item label="商品库存"  prop="goods_number">
          <el-input v-model="editForm.goods_number" type="number"></el-input>
        </el-form-item>
        <el-form-item label="商品分类" prop="goods_cat1">
          <el-cascader
                style="width:100%"
                v-model="editForm.goods_cat"
                :options="cateList"
                :props="cateProps"
                @change="handleChange"
              ></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfo"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      cateProps: {
        label: "cat_name",
        value: "_id",
      },
      cateList: [],
      // 查询参数对象
      queryInfo: {
        query: "",
        pagenum: 1,
        pagesize: 10,
      },
      // 商品列表
      goodsList: [],
      // 总数据条数
      total: 0,
      editDialogVisible:false,
      // 要修改的商品信息对象
      editForm:{},
      //修改表单的验证规则对象
      editFormRules:{
        goods_name:[
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        goods_price:[
          { required: true, message: "请输入商品价格", trigger: "blur" },
        ],
        goods_number:[
          { required: true, message: "请输入商品库存", trigger: "blur" },
        ],
        goods_cat:[
          { required: true, message: "请选择商品分类", trigger: "blur" },
        ]
    }
    };
  },
  created() {
    this.getGoodsList();
  },
  methods: {
    cateFormat(row){
      console.log(row.goods_cat)
      let id = row.goods_cat
      this.$http.get(`/categories/${id}`).then((res)=>{
        console.log(res.data)
        return res.data.cat_name
      })
        
    },
    saveState() {
      window.sessionStorage.setItem("activePath", "/welcome");
    },
    //   根据分页获取对应的商品列表
    async getGoodsList() {
      const res = await this.$http.get("/goods", { params: this.queryInfo });
      if (res.status === 200) {
        this.goodsList = res.data.goods;
        this.total = res.data.total;
      }
    },
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize;
      this.getGoodsList();
    },
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage;
      this.getGoodsList();
    },
    // 根据id删除商品
    async removeById(id) {
      const confirmResult = await this.$confirm(
        "此操作将永久删除该商品, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      if (confirmResult !== "confirm") {
        return this.$message.info("已经取消删除！");
      } else {
        const res = await this.$http.delete(`/goods/${id}`);
        if (res.status === 200) {
          this.$message.success("删除成功！");
          this.getGoodsList();
        }
      }
    },
    goAddpage() {
      this.$router.push("/goods/add");
    },
    // 获取所有商品分类数据
    async getCateList() {
      const res = await this.$http.get("/categories");
      if (res.status === 200) {
        this.cateList = res.data;
        // console.log(this.cateList);
      }
    },
    // 展示编辑用户的对话框
    async showEditDialog(id) {
      this.getCateList();
      const res = await this.$http.get(`/goods/${id}`);
      console.log(res)
      if (res.status === 200) {
        console.log(res)
        this.editForm = res.data;
      }
      this.editDialogVisible = true;
    },
    // 修改商品信息并提交
    editUserInfo(){
        this.$refs.editFormRef.validate(async valid=>{
            console.log(valid)
            if(!valid){
                return
            }else{
                // 发起修改商品信息的数据请求
                const res = await this.$http.put(`/goods/${this.editForm._id}`,{
                    goods_name:this.editForm.goods_name,
                    goods_price:this.editForm.goods_price,
                    goods_number:this.editForm.goods_number,
                    goods_cat:this.editForm.goods_cat
                })
                if(res.status === 200){
                    // 关闭对话框
                    this.editDialogVisible = false
                    // 刷新数据列表
                    this.getGoodsList()
                    // 提示修改成功
                    this.$message.success('商品信息修改成功！')
                }
            }
        })
    },
    // 监听修改商品对话框的关闭事件
    editDialogClosed(){
        this.$refs.editFormRef.resetFields()
    },
    handleChange() {
      console.log(this.editForm.goods_cat);
    },
  },
};
</script>

<style lang="less" scoped>
</style>